/*
 * Copyright 2007-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.ymate.platform.examples.base;

import net.ymate.platform.webmvc.context.WebContext;
import org.apache.commons.lang.StringUtils;

import java.io.Serializable;

/**
 * @author 刘镇 (suninformation@163.com) on 16/3/13 下午11:55
 * @version 1.0
 */
public class UserSessionBean implements Serializable {

    private String uid;

    private String email;

    private String nickname;

    private String photo;

    private long lastActivateTime;

    private UserSessionBean(String uid, String email) {
        this.uid = uid;
        this.email = email;
        this.lastActivateTime = System.currentTimeMillis();
    }

    /**
     * @param uid   用户UID
     * @param email 登录邮件
     * @return 创建UserSessionBean对象并存入当前会话中
     */
    public static UserSessionBean create(String uid, String email) throws Exception {
        if (StringUtils.isBlank(uid) || StringUtils.isBlank(email)) {
            throw new IllegalArgumentException("uid and email cannot be empty");
        }
        UserSessionBean _sessionBean = new UserSessionBean(uid, email);
        WebContext.getContext().getSession().put(UserSessionBean.class.getName(), _sessionBean);
        return _sessionBean;
    }

    /**
     * @return 获取当前会话中的UserSessionBean对象, 若不存在将返回null值
     */
    public static UserSessionBean current() {
        return (UserSessionBean) WebContext.getContext().getSession().get(UserSessionBean.class.getName());
    }

    /**
     * @return 更新会话最后活动时间(毫秒)
     */
    public UserSessionBean touch() {
        this.lastActivateTime = System.currentTimeMillis();
        return this;
    }

    public String getUid() {
        return uid;
    }

    public String getEmail() {
        return email;
    }

    public UserSessionBean setNickname(String nickname) {
        this.nickname = nickname;
        return this;
    }

    public String getNickname() {
        return nickname;
    }

    public String getPhoto() {
        return photo;
    }

    public UserSessionBean setPhoto(String photo) {
        this.photo = photo;
        return this;
    }

    public long getLastActivateTime() {
        return lastActivateTime;
    }
}
